from django.shortcuts import render
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django import http

# Create your views here.


class QQUserView(View):
    """处理授权后的回调
    GET /oauth_callback/
    """

    def get(self,request):
        """处理授权的回调逻辑"""
        code = request.GET.get('code')
        if not code:
            return http.JsonResponse({'code':400,'errmsg':'缺少code'})

        # 创建SDK的对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # 使用code获取access_token
            access_token = oauth.get_access_token(code)
            # 使用access_token获取openID
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            return http.JsonResponse({'code':400,'errmsg':'OAuth2.0认证失败'})

        # 使用openid去判断当前的QQ用户是否已经绑定过美多商城的用户

class QQURLView(View):
    """QQ登录扫码链接
    GET /qq/authorization/
    """

    def get(self,request):
        """提供QQ登录扫码链接"""
        #接受next参数
        next = request.GET.get('next','/')

        # 创建OAuthQQ
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)

        # 调用提供QQ登录扫码链接的接口函数
        login_url = oauth.get_qq_url()

        # 响应结果
        return http.JsonResponse({'code':0,'errmsg':'OK','login_url':login_url})
